package demo04ProxyPattern.cglibDynamicProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: WangPeng
 * @createTime: 2022/11/09 17:54
 * @description:
 * @version: v1.0
 */
public class ProxyFactory implements MethodInterceptor {

    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }
    public Object getInstance(){
        //创建一个工具---生成代理对象
        Enhancer enhancer=new Enhancer();
        //指定被代理的的父类
        enhancer.setSuperclass(target.getClass());
        //代理的回调方法
        enhancer.setCallback(this);
        return enhancer.create();
    }
    //执行被代理的方法时，会执行该方法。
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        introduce();
        watch();
        //调用被代理对象的方法
        Object result = method.invoke(target, objects);
        return result;
    }

    public void watch(){
        System.out.println("中介带你看房");
    }
    public void introduce(){
        System.out.println("房屋介绍");
    }
}
